const Core = require('./Core');
const Redis = require('./redis');
const Mysql = require('./mysql');
const SpiderQueue = require('./spiderQueue');

const client = new Core();

/** 修改队列并行数量 */
client.addEventListener('config', async config => {
  console.log('收到配置数据', config);
  const {room_queue, redisUrl, mysqlConfig} = config;

  const redis = new Redis(redisUrl);
  const mysql = new Mysql();
  await mysql.init(mysqlConfig);
  const status = {
    spider: {finish: 0, wait: 0, error: 0},
    save: {finish: 0, wait: 0, error: 0},
  };

  const [spiderQueue, roomQueue] = SpiderQueue({client, mysql, redis, status});
  spiderQueue.concurrency = room_queue;

  /**
   * 上传任务情况记录
   */
  setInterval(() => {
    status.spider.wait = spiderQueue.length() + spiderQueue.running();
    status.save.wait = roomQueue.length() + roomQueue.running();
    client.emit('status', status);
  }, 5000);

  /** 接收任务数据 */
  client.addEventListener('task', task => {
    console.log('接收任务', JSON.stringify(task));

    //优先级，只能在priorityQueue时使用
    // const priority = task.type === 'room' ? 1 : 0;
    // queue.push(task, priority);
    spiderQueue.push(task);
  });

});
